<template>
  <div>
    <a-input
      :size="size"
      v-model:value="code"
      :placeholder="placeholder"
      :addonBefore="addonBefore"
      :addonAfter="addonAfter"
      :disabled="disabled"
      readonly
    >
      <template #prefix v-if="prefix">
        <Icon :icon="prefix" />
      </template>
      <template #suffix v-if="suffix">
        <Icon :icon="suffix" />
      </template>
    </a-input>
  </div>
</template>
<script lang="ts" setup>
  import { ref, watch } from 'vue';
  import { generateCodeRule } from '/@/api/system/code';
  import { Icon } from '/@/components/Icon';

  const props = defineProps({
    value: String,
    size: String,
    placeholder: String,
    addonBefore: String,
    addonAfter: String,
    prefix: String,
    suffix: String,
    autoCodeRule: String,
    disabled: {
      type: Boolean,
      default: false,
    },
  });

  const code = ref('');
  const emit = defineEmits(['update:value']);

  watch(
    () => props.autoCodeRule,
    async (val) => {
      if (!!val) {
        code.value = await generateCodeRule(val);
        emit('update:value', code.value);
      }
    },
    {
      immediate: true,
    },
  );
  watch(
    () => props.value,
    (val) => {
      code.value = val || '';
    },
    {
      immediate: true,
    },
  );
</script>
